<template>
  <div v-if="vipDetail">
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="编辑会员资料"
      width="900px"
    >
      <div v-loading="dialogLoading" class="dialog-edit-info" element-loading-text="修改中">
        <!-- 修改表单 -->
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          class="demo-form-inline"
          label-width="120px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="会员姓名："
              >{{ vipDetail.member.name?vipDetail.member.name:vipDetail.customer.nickName }}</el-form-item>
              <el-form-item prop="phone" label="会员手机：">
                <el-input v-model="form.phone" :maxlength="11" />
              </el-form-item>
              <el-form-item label="会员生日：" class="date" prop="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  :picker-options="birthdayPickerOptions"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择生日"
                />
              </el-form-item>
              <el-form-item prop="address" label="详细地址：">
                <el-input v-model="form.address" type="text" />
              </el-form-item>
              <el-form-item prop="work" label="所在行业：">
                <el-input v-model="form.work" maxlength="12" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员卡号：">{{ vipDetail.member.cardNo?vipDetail.member.cardNo:"无" }}</el-form-item>
              <el-form-item prop="email" label="会员邮箱：">
                <el-input v-model="form.email" />
              </el-form-item>
              <el-form-item prop="idCard" label="身份证号：">
                <el-input v-model="form.idCard" :maxlength="18" />
              </el-form-item>
              <el-form-item prop="education" label="教育背景：">
                <el-input v-model="form.education" />
              </el-form-item>
              <el-form-item prop="income" label="年收入：">
                <el-input v-model="form.income" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="爱好：" class="form_hobby">
            <div
              v-for="(item,index) in form.hobby"
              :key="index"
              class="form-hobby-val app-border-color-primary"
            >
              <span>{{ item }}</span>
              <i class="el-icon-close" @click="delHobby(index)" />
            </div>
            <el-button type="primary" icon="el-icon-plus" size="small" circle @click="addHobby" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button size="small" round type="primary" @click="onSubmit('form')">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { updateVipInfo } from '@/api/vip'
import {
  validateMobilePhone,
  validateEMail,
  validateIDCard,
  validateStrLen
} from '@/utils/validate.js'
export default {
  props: {
    vipDetail: {
      type: Object,
      require: true
    }
  },
  data() {
    /**
       * 表单校验方法相关
       */
    // 手机号
    const validateTelPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else if (!validateMobilePhone(value)) {
        callback(new Error('请输入正确手机号'))
      } else {
        callback()
      }
    }
    // 邮箱
    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateEMail(value)) {
        callback(new Error('请输入正确邮箱号'))
      } else {
        callback()
      }
    }
    // 身份证
    const validateIdCard = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateIDCard(value)) {
        callback(new Error('请输入正确身份证号码'))
      } else {
        callback()
      }
    }
    // 地址
    const validateAddress = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateStrLen(value, 200)) {
        callback(new Error('长度不超过100个汉字或200个字符'))
      } else {
        callback()
      }
    }
    // 教育
    const validateEducation = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateStrLen(value, 20)) {
        callback(new Error('长度不超过10个汉字或20个字符'))
      } else {
        callback()
      }
    }
    // 行业
    const validateWork = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (value.length > 12) {
        callback(new Error('长度超过限制'))
      } else {
        callback()
      }
    }
    const validateIncome = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateStrLen(value, 20)) {
        callback(new Error('长度不超过10个汉字或20个字符'))
      } else {
        callback()
      }
    }
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        phone: [
          {
            required: true,
            validator: validateTelPhone,
            trigger: ['blur', 'change']
          }
        ],
        birthday: [
          {
            required: true,
            message: '请输入生日日期',
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {
            validator: validateEmail,
            trigger: ['blur', 'change']
          }
        ],
        idCard: [
          {
            validator: validateIdCard,
            trigger: ['blur', 'change']
          }
        ],
        address: [
          {
            validator: validateAddress,
            trigger: ['blur', 'change']
          }
        ],
        education: [
          {
            validator: validateEducation,
            trigger: ['blur', 'change']
          }
        ],
        work: [
          {
            validator: validateWork,
            trigger: ['blur', 'change']
          }
        ],
        income: [
          {
            validator: validateIncome,
            trigger: ['blur', 'change']
          }
        ]
      },
      birthdayPickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      // 配置
      dialogVisible: false,
      dialogLoading: false,
      resolve: null,
      reject: null,
      // 状态
      form: {
        address: '',
        birthday: '',
        education: '',
        email: '',
        hobby: '',
        idCard: '',
        income: '',
        phone: '',
        work: ''
      }
    }
  },
  methods: {
    open() {
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
      this.vipDetail.memberExtendInfo.phone = this.vipDetail.member.phone
      this.form = JSON.parse(JSON.stringify(this.vipDetail.memberExtendInfo))
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
       *  按钮组
       */
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm(
            `您确定要对会员${this.vipDetail.member.name}作信息变更, 是否继续?`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              center: true,
              roundButton: true
            }
          ).then(() => {
            const data = JSON.parse(JSON.stringify(this.form))
            data.hobby = data.hobby === [] ? '' : data.hobby.join(',')
            this.dialogLoading = true
            delete data.firstConsumeShop
            delete data.firstRechargeShop
            delete data.id
            delete data.categoryAward
            updateVipInfo(data)
              .then(res => {
                this.dialogLoading = false
                this.$notify({
                  title: '成功',
                  message: '会员信息已变更成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.$refs.form.resetFields()
                this.resolve && this.resolve()
                this.hide()
              })
              .catch(res => {
                this.dialogLoading = false
              })
          })
        }
      })
    },

    // 新增爱好
    addHobby() {
      this.$prompt('', '请输入爱好', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        roundButton: true,
        inputValidator: this.validateHobby
      }).then(({ value }) => {
        this.form.hobby.push(value)
        this.form.hobby = [...new Set(this.form.hobby)]
      })
    },

    // 校验兴趣爱好
    validateHobby(value) {
      if (value == null || value.trim() === '') {
        return '请输入兴趣爱好'
      } else if (!validateStrLen(value, 20)) {
        return '长度不超过10个汉字或20个字符'
      }
    },

    // 删除爱好
    delHobby(index) {
      this.form.hobby.splice(index, 1)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .dialog-edit-info {
    .el-date-editor .el-input {
      width: 100%;
    }
    .form-hobby-val {
      display: inline-block;
      height: 30px;
      padding: 0 5px 0 10px;
      margin-right: 10px;
      border-width: 1px;
      border-style: solid;
      border-radius: 5px;
      line-height: 30px;
      font-size: 14px;
      color: $dark-font-color;
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  .dialog-edit-info {
    .date {
      .el-date-editor {
        width: 100%;
      }
    }
  }
</style>
